<?php
/**
 * Created by litong on Date: 2019/2/25 0025 上午 8:18
 */
class TabRows extends RecursiveIteratorIterator{
  function __construct($it) {
    parent::__construct($it,self::LEAVES_ONLY);
  }
  function current() {
    return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
  }
  function beginChildren() {
    echo "<tr>";
  }
  function endChildren() {
    echo "</tr>" . "\n";
  }
}
$host="localhost";$username="root";$password="";$dbname="php_study";
$sql="SELECT id, firstname, lastname FROM my_guests";
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
try{
  $connection = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  $connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  $statement = $connection->prepare($sql);
  $statement->execute();
  $bool=$statement->setFetchMode(PDO::FETCH_ASSOC);//将结果关联为数组,返回值是true或false;
  $all = $statement->fetchAll(); //返回一个数组
  foreach(new TabRows(new RecursiveArrayIterator($all)) as $k=>$v){
    echo $v;
  }
}catch(PDOException $e){
  echo $e->getMessage();
}
echo "</table>";